import { emitter } from 'src/emitter';
import { onMounted, onUnmounted } from 'vue';

const heartCheck: Record<string, any> = {
  timeout: 60 * 1000,
  timer: null,
  serverTimer: null,
  reset() {
    //重置心跳
    this.timer && clearTimeout(this.timer);
    this.serverTimer && clearTimeout(this.serverTimer);
  },
  start(ws: any) {
    //开始心跳检测
    this.reset();
    this.timer = setTimeout(() => {
      // '发送心跳,后端收到后，返回一个心跳消息'
      // onmessage拿到返回的心跳就说明连接正常
      try {
        if (ws.readyState == ws.OPEN) {
          ws.send('ping');
        } else {
          //异常断开连接
          heartCheck.reset();
          ws.close();
        }
      } catch (error) {
        heartCheck.reset();
        ws.close();
      }
      this.serverTimer = setTimeout(() => {
        // 如果超过一定时间还没响应(响应后触发重置)，说明后端断开了
        ws.close(); //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
      }, this.timeout);
    }, this.timeout);
  },
};

export const useWebsocket = () => {
  let lockReconnect = false;
  const ip = process.env.NODE_ENV === 'production' ? window.location.host : '10.25.105.86';
  // const ip = process.env.NODE_ENV === 'production' ? window.location.host : '192.168.10.201';
  let ws: any;
  const initWebSocket = () => {
    ws = new WebSocket(`ws:/${ip}:8079`);
    ws.onopen = websocketonopen;
    ws.onmessage = websocketonmessage;
    ws.onerror = websocketonerror;
    ws.onclose = websocketclose;
  };
  const websocketonopen = () => {
    console.log('WebSocket连接成功', ws.readyState);
    heartCheck.start(ws);
    const actions = {
      topics: 'CRANE_WEBSOCKET,processStatus,trackMatA,trackMatB,blankingTable,cGateStatus',
      type: 'REGISTER',
    };
    ws.send(JSON.stringify(actions));
  };
  const websocketonmessage = (event: any) => {
    const { data } = event;
    if (data != 'pong') {
      const { topic, data: data1 } = JSON.parse(data);
      if (topic !== 'CRANE_WEBSOCKET') {
        console.log(topic, data1);
      }
      emitter.emit('websocket', { topic: topic, data: data1 });
    } else {
      heartCheck.start(ws);
    }
  };
  const websocketonerror = (e: any) => {
    console.log(`WebSocket连接发生错误:${e.code},${e.reason},${new Date().toLocaleString()}`);
    reconnect();
  };
  const websocketclose = (e: any) => {
    console.log(`WebSocket断开连接:${e.code},${e.reason},${new Date().toLocaleString()}`);
    reconnect();
  };
  const reconnect = () => {
    if (lockReconnect) {
      return;
    }
    console.log('尝试重连');
    lockReconnect = true;
    setTimeout(() => {
      // 不做限制 连不上一直重连
      //this.maxReconnect--;
      initWebSocket();
      lockReconnect = false;
    }, 10 * 1000);
  };
  onMounted(() => {
    initWebSocket();
  });
  onUnmounted(() => {
    ws.cloce();
  });
};
